//
//  HYTextField.m
//  HaiYue
//
//  Created by skyline on 2018/1/9.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYTextField.h"
@interface HYTextField ()<UITextFieldDelegate>
@property (nonatomic, strong)UIButton *verifyBtn;
@property (nonatomic, strong) CCTime *timer;
@end
@implementation HYTextField
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.delegate = self;
        self.borderStyle = UITextBorderStyleNone;
        self.backgroundColor = [UIColor whiteColor];
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
    }
    return self;
}
- (instancetype)initWithPlaceholder:(NSString *)placeholder
{
    self = [super init];
    if (self)
    {
        self.delegate = self;
        self.placeholder = placeholder;
        self.borderStyle = UITextBorderStyleNone;
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = 5;
        self.backgroundColor = [UIColor whiteColor];
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
    }
    return self;
}

- (UIButton *)verifyBtn
{
    if (!_verifyBtn)
    {
        _verifyBtn = [[UIButton alloc]init];
        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        _verifyBtn.backgroundColor = THEME_COLOR;
        _verifyBtn.layer.masksToBounds = YES;
        _verifyBtn.layer.cornerRadius = 5.0;
        [_verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_verifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_verifyBtn addTarget:self action:@selector(actionForVerifyBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_verifyBtn.titleLabel sizeToFit];
        _verifyBtn.bounds = CGRectMake(0, 0, _verifyBtn.titleLabel.bounds.size.width + 20, 0);
        [self addSubview:_verifyBtn];
        [_verifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self);
            make.top.equalTo(self);
            make.bottom.equalTo(self);
            make.width.mas_equalTo(self.verifyBtn.bounds.size.width);
        }];
    }
    return _verifyBtn;
}

- (CCTime *)timer
{
    if (!_timer)
    {
        _timer = [[CCTime alloc]init];
    }
    return _timer;
}

- (void)setVerify:(BOOL)verify
{
    if (_verify != verify)
    {
        _verify = verify;
        if (_verify)
        {
            self.verifyBtn.hidden = NO;
            [self clearButtonRectForBounds:CGRectMake(0, 0, self.bounds.size.width + 20, self.bounds.size.height)];
        }
    }
}

- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
    if (_placeholderFont != placeholderFont)
    {
        _placeholderFont = placeholderFont;
        [self setValue:_placeholderFont forKeyPath:@"_placeholderLabel.font"];
    }
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    if (_placeholderColor != placeholderColor)
    {
        _placeholderColor = placeholderColor;
        [self setValue:_placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
    }
}

- (void)setType:(HYTextFieldType)type
{
    if (_type != type)
    {
        _type = type;
        switch (_type) {
            case HYTextFieldTypeDefault:
                break;
            case HYTextFieldTypeAccount:
                self.keyboardType = UIKeyboardTypeASCIICapable;
                break;
            case HYTextFieldTypePhone:
                self.keyboardType = UIKeyboardTypeNumberPad;
                break;
            case HYTextFieldTypeName:
                break;
            case HYTextFieldTypePassword:
                break;
            case HYTextFieldTypeVerifyCode:
                self.keyboardType = UIKeyboardTypeNumberPad;
                break;
            case HYTextFieldTypeSearch:
                self.keyboardType = UIKeyboardTypeWebSearch;
                break;
            default:
                break;
        }
    }
}
- (void)actionForVerifyBtn:(UIButton *)sender
{
    //    _verifyBtn.userInteractionEnabled = sender.selected;
    
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(shouldVerifycationCode)] && sender.selected == NO)
    {
        BOOL canVerify = [self.hydelegate shouldVerifycationCode];
        if (canVerify)
        {
            //            _verifyBtn.userInteractionEnabled = sender.selected;
            sender.selected = !sender.selected;
            sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:THEME_COLOR;
            if (sender.selected)
            {
                [self.timer countDown:60 time:^(NSString *time) {
                    NSString *timestring = [NSString stringWithFormat:@"已获取(%@s)", time];
                    [self.verifyBtn setTitle:timestring forState:UIControlStateNormal];
                    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    
                } complete:^{
                    sender.selected = NO;
                    [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                    sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:THEME_COLOR;
                    
                    //                    [self performSelector:@selector(actionForVerifyBtn:) withObject:sender];
                }];
            }
            else
            {
                [_timer cancel];
            }
        }
    }
}

- (void)stopTimer
{
    if (_timer)
    {
        [self performSelector:@selector(actionForVerifyBtn:) withObject:_verifyBtn];
    }
}

- (void)setupLineWhenBeginEditing
{
    self.layer.borderColor = THEME_COLOR.CGColor;
    self.layer.borderWidth = CellBottomLineHeight;
}

- (void)setupLineWhenEndEditing
{
    self.layer.borderColor = [UIColor clearColor].CGColor;
    self.layer.borderWidth = 0;
}

// 添加通知监听见键盘弹出/退出
- (void)registerNotification
{
    [CCNotice addObs:self sel:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification obj:nil];
    [CCNotice addObs:self sel:@selector(keyboardWillShow:) name:UIKeyboardWillHideNotification obj:nil];
}

- (void)releaseNotification
{
    [CCNotice rmObs:self name:UIKeyboardWillShowNotification obj:nil];
    [CCNotice rmObs:self name:UIKeyboardWillHideNotification obj:nil];
}

//控制placeholder的位置
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds, GAP, 0);
}

//控制显示文本的位置
- (CGRect)textRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds, GAP, 0); //文字左边与leftview右边距离10
}

//控制编辑文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds, GAP, 0); //文字左边与leftview右边距离10
}

//控制clearButton的位置
- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    CGRect clearRect = [super clearButtonRectForBounds:bounds];
    if (_verify)  clearRect.origin.x -= _verifyBtn.bounds.size.width;
    return clearRect;
}

//弹出键盘时候，判断是否遮挡输入框，
- (void)keyboardWillShow:(NSNotification *)notification
{
    if (!self.editing)
        return;
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = [aValue CGRectValue].size.height;//键盘的高度
    //获取键盘动画时间
    float time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //输入框在当前屏幕的坐标y
    CGFloat originMaxY = CGRectGetMaxY([self convertRect:self.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    //判断是否遮挡当前输入框，大于0遮挡，小于0没有
    CGFloat map = originMaxY + keyboardHeight - SCREEN_HEIGHT;
    
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(heightWhenKeyboardChange:animationInterval:)])
        [self.hydelegate heightWhenKeyboardChange:map animationInterval:time];
}

#pragma mark UITextFieldDelegate 事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self registerNotification];//注册通知
    [self setupLineWhenBeginEditing];//设置下划线颜色
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)])
        return [self.hydelegate textFieldShouldBeginEditing:textField];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//取消第一响应者
    [self releaseNotification];//释放通知
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(textFieldShouldReturn:)])
        return [self.hydelegate textFieldShouldReturn:textField];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string containsString:@" "]) return NO;
    
    else if ((self.type == HYTextFieldTypeAccount || self.type == HYTextFieldTypePassword) && ![string isNumberOrAlphabet] && ![string isEqualToString:@""]) return NO;
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(textField: shouldChangeCharactersInRange: replacementString:)])
        return [self.hydelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    return YES;
}   // return NO to not change text

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self setupLineWhenEndEditing];
    if (self.hydelegate && [self.hydelegate respondsToSelector:@selector(textFieldDidEndEditing:)])
        [self.hydelegate textFieldDidEndEditing:textField];
}

- (void)dealloc
{
    NSLog(@"dealloc ~~````~~~~~~~~~~~~~~~~~~~~~~~~");
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
